#!/bin/bash

pipe="pipe"
session=${@:1:1}
win=${@:2:1}
input=${@:3:1}
speed="0.3"
ex_arg_index=3

ps=$(screen -ls | grep $pipe)
if [ -z "$ps" ]; then
    screen -dmS $pipe
    olv pipe $@
    exit
fi

case "$session" in
    *.input)
	session="pipe"
	win="1"
	input=${@:1:1}
	ex_arg_index=1
    ;;
esac

case "$ps" in
    *Detached*)
	sleep 2 && olv pipe $session init args $@ &
	screen -mddr $pipe
	exit
    ;;
    *Attached*)
	session="pipe"
	win="1"
    ;;
esac

#add function: if no pipe screen, add one
#pipescreen=$(screen -S work -Q windows | grep pipe)
if [ "start" = "$win" ] || [ "init" = "$win" ]; then
    sessions=$(screen -ls | grep $pipe)
    if [ -z "$sessions" ]; then
	screen -dmS $pipe
	olv pipe $session start
	exit
    fi

    case "$sessions" in
	*Detached*)
	    sleep 2 && olv pipe $session start &
	    screen -mddr $pipe
	    exit
	;;
    esac

    args=$(echo "$@" | sed 's/.*args //')
    
    screen -S $pipe -X split
    screen -S $pipe -X resize -v 45%
    screen -S $pipe -X screen -t pipe
    screen -S $pipe -X focus down
    screen -S $pipe -X other
    sleep 2
    screen -S $pipe -X stuff "olv pipe $args"
    screen -S $pipe -p 1 -X logfile /tmp/olvpipe.log
    screen -S $pipe -p 1 -X log on
    exit
elif [ "kill" = "$win" ]; then
    psid=$(echo "$ps" | sed 's/\..*//;s/[^0-9]//')
    kill $psid
    exit
elif [ "last" = "$session" ]; then
    if [ -f "$HOME/.olv_pipe_last" ]; then
	cat "$HOME/.olv_pipe_last"
	exit
    fi
fi

#save last pipe to file
echo "$@" > $HOME/.olv_pipe_last

#echo $session $win $file
#session=pts-1.oliviapop
#win=3
#cmd="screen -S $session -p $win -X stuff"

if [ "l" = "${input:0:1}" ]; then
    echo ${@:4} > /tmp/line
    screen -S $session -p $win -X stuff "$(cat /tmp/line)^M"
elif [ ! -f "$input" ]; then
    input="$HOME/src/olv/input/$input"
fi
prompts=$(expr $# - $ex_arg_index)
prompt=""
p_index=0
paste=""
copy=""

count=$(expr $(cat $input | wc -l) + 1)
i=1
while [ $count -gt $i ]; do
    l=$(expr $i - 1)
    line=($(sed "$i!d" $input))
    if [ ! -z "$prompt" ]; then
	line=($(sed "$i!d" $input | sed "s~\[result\]~$prompt~g"))
	prompt=""
	p_index=$(expr $p_index + 1 )
    elif [ ! -z "$copy" ]; then
	line=($(sed "$i!d" $input | sed "s~\[$copy\]~$paste~g"))
	copy=""
	paste=""
    fi
    if [ "pipe" = "${line[0]}" ]; then
	if [ "import" = "${line[1]}" ]; then
	    if [ "py" = "${line[2]}" ]; then
		func_def="def"
	    fi
	    func_name=${line[3]}
	    from=$(expr length "$(echo ${line[@]} | sed 's/from.*/from/;s/[^ ]//g')" + 1)
	    import=${line[$from]}
	    after=$(expr length "$(echo ${line[@]} | sed 's/after.*/after/;s/[^ ]//g')" + 1)
	    until=$(expr length "$(echo ${line[@]} | sed 's/until.*/until/;s/[^ ]//g')" + 1)
	    include=$(expr length "$(echo ${line[@]} | sed 's/include.*/include/;s/[^ ]//g')" + 1)
	    replace=$(expr length "$(echo ${line[@]} | sed 's/replace.*/replace/;s/[^ ]//g')" + 1)
	    if [ -f "$import" ]; then
		#echo "Importing $func_name from $import"
		func_line=$(grep -n "$func_def $func_name" $import | sed 's/[^0-9]*:.*//')
		#stop_at=$(grep -nB $func_line ${line[$after]} $import | head -1 | sed 's/[^0-9]*:.*//')
		func=$(sed -n "/$func_def $func_name/,/$func_def/p" $import)
		#section 1: function def - $after
		section=$(echo "$func" | sed -n "/$func_def $func_name/,/${line[$after]}/p")
		#section 2: after + 1 - until
		section+=$(echo -e "\n\r")$(echo "$func" | sed -n "/${line[$(expr $after + 1)]}/,/${line[$until]}/p" | sed '$ d' | sed 's/elif/if/')
		#section 3: include - end of function
		section+=$(echo -e "\n\r")$(echo "$func" | sed -n "/${line[$include]}/,/^$/p")
		section=$(echo "$section" | sed -e $(echo "${line[$replace]}") | sed '/^$/d')
		echo "$section" > tmp.py
		#screen -S $session -p $win -X stuff "from tmp import $func_name^M"
	    else
		echo "Import file doesn't exist: $import"
	    fi
	elif [ "copy" = "${line[1]}" ]; then
	    if [ -f "$(which ${line[2]})" ]; then
		copy=${line[@]:2}
		paste=$(${line[@]:2})
	    fi
	elif [ "speed" = "${line[1]}" ]; then
	    speed="${line[@]:1}"
	elif [ "backspace" = "${line[1]}" ]; then
	    if [ -z "${line[2]}" ]; then
		screen -S $session -p $win -X stuff "^H"
	    else
		times=$(expr ${line[2]} + 1)
		while [ 1 -le "$times" ]; do
		    screen -S $session -p $win -X stuff "^H"
		    times=$(expr $times - 1)
		done
	    fi
	elif [ "trap" = "${line[1]}" ]; then
	    trapline="${line[@]:2}"
	    trapfunc() {
		screen -S $session -p $win -X stuff "$trapline^M"
		exit
	    }
	    trap 'trapfunc' SIGINT
	elif [ "goto" = "${line[1]}" ]; then
	    if [ "line" = "${line[2]}" ]; then
		i=${line[3]}
	    elif [ "string" = "${line[2]}" ]; then
		i=$(grep -n "${line[@]:2}" $input | head -1 | sed 's/:.*//')
	    else
		i=${line[@]:1}
	    fi
	elif [ "prompt" = "${line[1]}" ]; then
	    if [ "$prompts" -gt "$p_index" ]; then
		prompt="${@:$(expr $p_index + $ex_arg_index + 1):1}"
	    else
		line="${line[@]:2}"
		read -p "$line " prompt
	    fi
	elif [ "wait" = "${line[1]}" ]; then
	    line="${line[@]:2}"
	    if [ -z "$line" ]; then
		line="Waiting for input..."
	    fi
	    read -p "$line "
	elif [ "exit" = "${line[1]}" ] || [ -f "$(which ${line[1]})" ]; then
	    ${line[@]:1}
	fi
    else
	l=${line[@]}
	lcount=${#l}
	while [ "12" -lt "$lcount" ]; do
	    #echo "$lcount : ${l:0:12}"
	    c=${l:0:12}
	    #echo "pipe $lcount: $c"
	    screen -S $session -p $win -X stuff "$c"
	    l=${l:12}
	    lcount=${#l}
	done
	screen -S $session -p $win -X stuff "$l^M"
	#echo "end: $lcount : ${l}"
	#echo ${line[@]} > /tmp/line
	#screen -S $session -p $win -X stuff "${line[@]}^M"
	#screen -S $session -p $win -X stuff "$(cat /tmp/line)^M"
	sleep $speed
    fi
    
    i=$[$i+1]
done
